package com.nys.cqhttp.message.factory.impl;

import com.alibaba.fastjson.JSONObject;
import com.nys.cqhttp.mapper.ChinaCityMapper;
import com.nys.cqhttp.message.factory.IMessageHandler;

import com.nys.cqhttp.message.pojo.NowPojo;
import com.nys.cqhttp.model.ChinaCity;
import com.nys.cqhttp.model.ChinaCityExample;
import com.nys.cqhttp.model.Massage;
import com.nys.cqhttp.param.Context;
import com.nys.cqhttp.util.BeanUtils;
import com.nys.cqhttp.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * DirectUrlMessageHandler
 *
 * @author nysheng
 * @version 1.0.0
 * @description 天气
 * @date 2021/12/28 19:53
 */
@Slf4j
@Component
public class TianQiMessageHandler implements IMessageHandler {
  @Autowired
  private ChinaCityMapper chinaCityMapper;

  private static TianQiMessageHandler tianQiMessageHandler;
  @PostConstruct
  public void init() throws Exception {
    tianQiMessageHandler = this;
    chinaCityMapper= this.chinaCityMapper;
  }
  @Override
  public List<String> listHandler(Massage messagePojo, Context context) {
    return Arrays.asList(handler(messagePojo, context));
  }

  @Override
  public String handler(Massage messagePojo, Context context) {
    String[] split = context.getMessageParam().getMessage().split("-");
    ChinaCityExample example = new ChinaCityExample();
    ChinaCityExample.Criteria criteria = example.createCriteria();
    criteria.andLocationnamezhEqualTo(split[1]);
    List<ChinaCity> chinaCities = tianQiMessageHandler.chinaCityMapper.selectByExample(example);

    String url = String.format(messagePojo.getValue(), chinaCities.get(0).getLocationid());

    RestTemplate restTemplate = SpringContextUtil.getBean("restTemplate");

    try {
      JSONObject jsonObject = JSONObject.parseObject(restTemplate.getForEntity(url, String.class).getBody());
      log.info(jsonObject.toJSONString());
      NowPojo now = jsonObject.getObject("now", NowPojo.class);
      log.info(now.toString());
      return now.toString();
    } catch (Exception e) {
      return null;
    }
  }
}
